import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message, Upload } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import GroupSidebar from './GroupSidebar';
import DocumentView from './DocumentView';
import { fetchGroups, saveGroups } from '../api/group';
import { fetchDocumentsByGroup, fetchDocumentContent, saveDocument } from '../api/document';
import { RcFile } from "antd/es/upload";
import ResizablePanel from "../components/ResizablePanel";
import '../assets/css/ResizablePanel.css';

interface DGroup {
    id: string;
    title: string;
    baseId: string;
    sortOrder: number;
}

interface Document {
    id: string;
    groupId: string;
    baseId: string;
    content: string;
    title?: string;
    sortOrder: number;
}

interface PageParams {
    baseId: string;
    current: number;
    size: number;
}

interface GroupsResponse {
    records: DGroup[];
    total: number;
    size: number;
    current: number;
}

const HomePage: React.FC = () => {
    const [groups, setGroups] = useState<DGroup[]>([]);
    const [docs, setDocs] = useState<Record<string, Document[]>>({});
    const [activeGroup, setActiveGroup] = useState<string | null>(null);
    const [activeDoc, setActiveDoc] = useState<Document | null>(null);
    const [docContent, setDocContent] = useState<string>('');
    const [loadingDoc, setLoadingDoc] = useState<boolean>(false);
    const [groupModalVisible, setGroupModalVisible] = useState(false);
    const [documentModalVisible, setDocumentModalVisible] = useState(false);
    const [importModalVisible, setImportModalVisible] = useState(false);
    const [loading, setLoading] = useState(false);
    const [importLoading, setImportLoading] = useState(false);
    const [fileList, setFileList] = useState<any[]>([]);
    const [groupForm] = Form.useForm();
    const [documentForm] = Form.useForm();
    const [importForm] = Form.useForm();

    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 5,
        total: 0,
        hasMore: true
    });

    const [loadingMore, setLoadingMore] = useState(false);
    const [pageParams] = useState<PageParams>({
        baseId: "d604f6c5a88adada1bee2f87b",
        current: 1,
        size: 5
    });

    const loadGroups = async (page = 1, append = false) => {
        try {
            setLoadingMore(true);
            const params = { ...pageParams, current: page, size: pagination.pageSize };
            const response = await fetchGroups(params) as unknown as GroupsResponse;

            if (response && response.records) {
                const newGroups = response.records || [];
                setGroups(prev => append ? [...prev, ...newGroups] : newGroups);

                setPagination(prev => ({
                    ...prev,
                    current: page,
                    total: response.total || 0,
                    hasMore: (response.records?.length || 0) >= pagination.pageSize
                }));
            }
        } catch (error) {
            message.error('加载分组失败');
        } finally {
            setLoadingMore(false);
        }
    };

    useEffect(() => {
        loadGroups(1, false);
    }, []);

    const handleGroupChange = (groupId: string) => {
        setActiveGroup(groupId);
        if (!docs[groupId]) {
            fetchDocumentsByGroup(groupId).then((list: Document[]) => {
                setDocs(prev => ({ ...prev, [groupId]: list || [] }));
            });
        }
    };

    const handleDocClick = (doc: Document) => {
        setActiveDoc(doc);
        setLoadingDoc(true);
        fetchDocumentContent(doc.id).then((content: string) => {
            setDocContent(content || 'No content available');
            setLoadingDoc(false);
        });
    };

    const handleAddGroup = () => setGroupModalVisible(true);

    const handleGroupSubmit = async () => {
        try {
            const values = await groupForm.validateFields();
            setLoading(true);

            const newGroup: Partial<DGroup> = {
                title: values.title,
                baseId: pageParams.baseId,
                sortOrder: groups.length + 1
            };

            const createdGroup = await saveGroups(newGroup) as DGroup;
            setGroups(prev => [...prev, createdGroup]);
            message.success('分组创建成功');
            setGroupModalVisible(false);
            groupForm.resetFields();
        } catch (error) {
            message.error('创建分组失败');
        } finally {
            setLoading(false);
        }
    };

    const handleAddDocument = () => {
        if (!activeGroup) {
            message.warning('请先选择一个分组');
            return;
        }
        setDocumentModalVisible(true);
    };

    const handleDocumentSubmit = async () => {
        try {
            const values = await documentForm.validateFields();
            setLoading(true);

            const newDocument: Partial<Document> = {
                title: values.title,
                content: values.content || '# 新文档\n请在此编辑内容',
                groupId: activeGroup!,
                baseId: pageParams.baseId,
                sortOrder: docs[activeGroup!]?.length || 0
            };

            const createdDocument = await saveDocument(newDocument) as Document;
            const completeDocument: Document = {
                ...createdDocument,
                title: createdDocument.title || '未命名文档',
                id: createdDocument.id || Date.now().toString(),
                groupId: createdDocument.groupId,
                baseId: createdDocument.baseId,
                content: createdDocument.content,
                sortOrder: createdDocument.sortOrder
            };

            setDocs(prev => ({
                ...prev,
                [activeGroup!]: [...(prev[activeGroup!] || []), completeDocument]
            }));

            message.success('文档创建成功');
            setDocumentModalVisible(false);
            documentForm.resetFields();
        } catch (error) {
            message.error('创建文档失败');
        } finally {
            setLoading(false);
        }
    };

    const handleDocumentUpdated = (updatedDoc: Document) => {
        setDocContent(updatedDoc.content);
        setActiveDoc(updatedDoc);
        
        // Update the document in the docs state
        setDocs(prev => {
            const groupDocs = prev[updatedDoc.groupId] || [];
            const updatedGroupDocs = groupDocs.map(doc =>
                doc.id === updatedDoc.id ? updatedDoc : doc
            );
            return { ...prev, [updatedDoc.groupId]: updatedGroupDocs };
        });
    };

    const handleImportDocument = () => {
        if (!activeGroup) {
            message.warning('请先选择一个分组');
            return;
        }
        setImportModalVisible(true);
    };

    const readFileContent = (file: File): Promise<string> => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (event) => {
                if (event.target?.result) {
                    resolve(event.target.result as string);
                } else {
                    reject(new Error('无法读取文件内容'));
                }
            };
            reader.onerror = () => reject(new Error('文件读取错误'));
            reader.readAsText(file);
        });
    };

    const handleImportSubmit = async () => {
        if (!fileList.length) {
            message.warning('请选择要导入的文件');
            return;
        }

        try {
            setImportLoading(true);
            const file = fileList[0].originFileObj;
            const content = await readFileContent(file);
            const fileName = file.name;
            const title = fileName.replace(/\.md$/i, '');

            const newDocument: Partial<Document> = {
                title: title,
                content: content,
                groupId: activeGroup!,
                baseId: pageParams.baseId,
                sortOrder: docs[activeGroup!]?.length || 0
            };

            const createdDocument = await saveDocument(newDocument) as Document;
            const completeDocument: Document = {
                ...createdDocument,
                title: title,
                id: createdDocument.id || Date.now().toString(),
                groupId: createdDocument.groupId,
                baseId: createdDocument.baseId,
                content: createdDocument.content,
                sortOrder: createdDocument.sortOrder
            };

            setDocs(prev => ({
                ...prev,
                [activeGroup!]: [...(prev[activeGroup!] || []), completeDocument]
            }));

            message.success('文档导入成功');
            setImportModalVisible(false);
            setFileList([]);
            importForm.resetFields();
        } catch (error) {
            message.error('导入文档失败');
        } finally {
            setImportLoading(false);
        }
    };

    const uploadProps = {
        onRemove: () => {
            setFileList([]);
            return true;
        },
        beforeUpload: (file: RcFile) => {
            const isMd = file.name.toLowerCase().endsWith('.md');
            if (!isMd) {
                message.error('只能上传Markdown文件 (.md)');
                return Upload.LIST_IGNORE;
            }

            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('文件大小不能超过2MB');
                return Upload.LIST_IGNORE;
            }

            setFileList([{
                uid: file.uid,
                name: file.name,
                status: 'done',
                originFileObj: file
            }]);
            return false;
        },
        fileList,
        maxCount: 1,
        accept: '.md',
    };

    const handleLoadMore = () => {
        if (!loadingMore && pagination.hasMore) {
            loadGroups(pagination.current + 1, true);
        }
    };

    return (
        <div style={{ height: '100vh', background: '#f5f7fa' }}>
            <ResizablePanel
                left={
                    <GroupSidebar
                        groups={groups}
                        docs={docs}
                        activeGroup={activeGroup}
                        activeDoc={activeDoc}
                        loadingMore={loadingMore}
                        pagination={pagination}
                        onGroupChange={handleGroupChange}
                        onDocClick={handleDocClick}
                        onAddGroup={handleAddGroup}
                        onAddDocument={handleAddDocument}
                        onImportDocument={handleImportDocument}
                        onLoadMore={handleLoadMore}
                    />
                }
                right={
                    <DocumentView
                        activeDoc={activeDoc}
                        docContent={docContent}
                        loadingDoc={loadingDoc}
                        onDocumentUpdated={handleDocumentUpdated}
                        onImportDocument={handleImportDocument}
                    />
                }
                initialLeftWidth={300}
                minLeftWidth={200}
                maxLeftWidth={500}
            />

            <Modal
                title="新建文档分组"
                open={groupModalVisible}
                onOk={handleGroupSubmit}
                onCancel={() => setGroupModalVisible(false)}
                confirmLoading={loading}
            >
                <Form form={groupForm} layout="vertical">
                    <Form.Item
                        name="title"
                        label="分组名称"
                        rules={[{ required: true, message: '请输入分组名称' }]}
                    >
                        <Input placeholder="请输入分组名称" />
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                title="新建文档"
                open={documentModalVisible}
                onOk={handleDocumentSubmit}
                onCancel={() => setDocumentModalVisible(false)}
                confirmLoading={loading}
                width={600}
            >
                <Form form={documentForm} layout="vertical">
                    <Form.Item
                        name="title"
                        label="文档标题"
                        rules={[{ required: true, message: '请输入文档标题' }]}
                    >
                        <Input placeholder="请输入文档标题" />
                    </Form.Item>
                    <Form.Item
                        name="content"
                        label="文档内容 (Markdown格式)"
                        rules={[{ required: true, message: '请输入文档内容' }]}
                    >
                        <Input.TextArea
                            placeholder="请输入Markdown格式的文档内容"
                            rows={10}
                            style={{ fontFamily: 'monospace' }}
                        />
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                title="导入文档"
                open={importModalVisible}
                onOk={handleImportSubmit}
                onCancel={() => {
                    setImportModalVisible(false);
                    setFileList([]);
                    importForm.resetFields();
                }}
                confirmLoading={importLoading}
                okText="导入"
                cancelText="取消"
            >
                <Form form={importForm} layout="vertical">
                    <Form.Item
                        name="file"
                        label="选择Markdown文件"
                        rules={[{ required: true, message: '请选择要导入的文件' }]}
                    >
                        <Upload.Dragger {...uploadProps}>
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined />
                            </p>
                            <p className="ant-upload-text">点击或拖拽文件到此处上传</p>
                            <p className="ant-upload-hint">
                                仅支持 .md 格式文件，文件大小不超过2MB
                            </p>
                        </Upload.Dragger>
                    </Form.Item>

                    <Form.Item
                        name="title"
                        label="文档标题（可选）"
                        tooltip="如果不填写，将使用文件名作为标题"
                    >
                        <Input placeholder="输入文档标题" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default HomePage;